package com.situ.hotel.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.hotel.entity.Emp;

// /*代表过滤所有的请求
@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter{
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("LoginFilter.init()");
	}
	

	// 在访问Servlet所有的请求之前，都会先经过Filter里面的这个doFilter方法，
	// 我们就可以在这里判断员工有没有登录
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		// 获取请求的路径，对于特殊例如完成登录流程的请求都不验证
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		// 和登录相关的就不去判断是否登录
		if ("/web/login.jsp".equals(servletPath) 
			|| "/loginServlet".equals(servletPath)
			|| servletPath.endsWith(".js")
			|| servletPath.endsWith(".css")
			|| servletPath.endsWith(".png")) {
			// 执行后面代码
			chain.doFilter(request, response);
		} else { // 需要判断是否登录
			HttpSession session = httpServletRequest.getSession();
			Emp emp = (Emp)session.getAttribute("emp");
			if (emp == null) {// 代表这个用户没有登录
				// 到登录界面
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/web/login.jsp");
				return;
			}
			
			// 已经登录，执行后面代码
			chain.doFilter(request, response);
		}
		
		
	}

	@Override
	public void destroy() {
		System.out.println("LoginFilter.destroy()");
	}

}
